package com.platform.modules.sys.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.Constant;
import com.platform.common.utils.Query;
import com.platform.modules.sys.dao.SysRoleDao;
import com.platform.modules.sys.entity.SysPerProcessEntity;
import com.platform.modules.sys.entity.SysRoleEntity;
import com.platform.modules.sys.service.SysPerProcessService;
import com.platform.modules.sys.service.SysRoleMenuService;
import com.platform.modules.sys.service.SysRoleOrgService;
import com.platform.modules.sys.service.SysRoleService;
import com.platform.modules.sys.service.SysUserRoleService;
import com.platform.modules.sys.service.SysUserService;

/**
 * @author 肖亮
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleOrgService sysRoleOrgService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysPerProcessService sysPerProcessService;

	@Override
	public IPage<SysRoleEntity> queryPage(Map<String, Object> params) {
		// 排序
		params.put("sidx", "T.CREATE_TIME");
		params.put("asc", false);
		IPage<SysRoleEntity> page = new Query<SysRoleEntity>(params).getPage();
		List<SysRoleEntity> roleList = baseMapper.selectSysRolePage(page, params);
		//遍历角色获取角色相关的菜单权限和流程权限
		for(SysRoleEntity sysRoleEntity:roleList){
			String roleId = sysRoleEntity.getRoleId();	
			//查询菜单权限
			List<String> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
			if(menuIdList !=null && menuIdList.size()>0){
				sysRoleEntity.setMenuIdList(menuIdList);
			}
			//查询流程权限
			List<String> processCodeList = sysPerProcessService.queryPerProcessCodeByRoleId(roleId);
			if(processCodeList !=null && processCodeList.size()>0){
				sysRoleEntity.setProcessIdList(processCodeList);
			}
		}
		return page.setRecords(roleList);
		
	}

	@Override
	public List<SysRoleEntity> selectListByMap(Map<String, Object> params) {
		return baseMapper.selectSysRolePage(params);
	}
	
	
	
	/**
	 * 根据userId 查询role
	 *
	 * @param params
	 *            查询参数
	 * @return List
	 */
	@Override
	public List<SysRoleEntity> queryRoleList(String userId) {
		return baseMapper.queryRoleList(userId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(SysRoleEntity role,String userId) {
		role.setCreateTime(new Date());
		this.save(role);

		// 检查权限是否越权
//		checkPrems(role);

		// 保存角色与菜单关系
		sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

		// 保存角色与机构关系
		sysRoleOrgService.saveOrUpdate(role.getRoleId(), role.getOrgNoList());
		
		//菜单集合
		List<String> menuIdList = role.getMenuIdList();
		if(menuIdList != null && menuIdList.size()>0){
			String roleId = role.getRoleId();
			sysRoleMenuService.saveOrUpdate(roleId,menuIdList);
		}
		//流程权限集合
		List<String> processCodeList = role.getProcessIdList();
//		if(processCodeList != null && processCodeList.size()>0){
			String roleCode = role.getRoleCode();
			sysPerProcessService.saveOrUpdate(roleCode, processCodeList,userId);
//		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysRoleEntity role,String userId) {
		this.updateById(role);

		// 检查权限是否越权
//		checkPrems(role);
        
		// 更新角色与菜单关系
		if(role != null && role.getMenuIdList() != null && role.getMenuIdList().size()>0){
			sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
		}
		
		// 保存角色与机构关系
		if(role != null && role.getOrgNoList() != null && role.getOrgNoList().size()>0){
			sysRoleOrgService.saveOrUpdate(role.getRoleId(), role.getOrgNoList());
		}
		
		//流程权限集合
		List<String> processIdList = role.getProcessIdList();
		String roleId = role.getRoleId();
		sysPerProcessService.saveOrUpdate(roleId, processIdList,userId);
		
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteBatch(String[] roleIds) {
		// 删除角色
		this.removeByIds(Arrays.asList(roleIds));

		// 删除角色与菜单关联
		sysRoleMenuService.deleteBatch(roleIds);

		// 删除角色与用户关联
		sysUserRoleService.deleteBatch(roleIds);

		// 删除角色与机构关联
		sysRoleOrgService.deleteBatch(roleIds);
	}

	@Override
	public List<String> queryRoleIdList(Map<String, Object> params) {
		return baseMapper.queryRoleIdList(params);
	}

	
	
	
	/**
	 * 检查权限是否越权
	 */
	private void checkPrems(SysRoleEntity role) {
		// 如果不是超级管理员，则需要判断角色的权限是否超过自己的权限
		if (Constant.SUPER_ADMIN.equals(role.getCreateUserId())) {
			return;
		}

		// 查询用户所拥有的菜单列表
		List<String> menuIdList = sysUserService.queryAllMenuId(role.getCreateUserId());

		// 判断是否越权
		if (!menuIdList.containsAll(role.getMenuIdList())) {
			throw new BusinessException("新增角色的权限，已超出你的权限范围");
		}
	}
}
